package projectsupporter.common.formbase;

import java.io.File;

import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;

import projectsupporter.common.control.Path;
import projectsupporter.common.logic.GlobalInfo;
import projectsupporter.common.logic.PlugUILogic.ImagePath;

import dbTools.DBToolEngine;

public class FolderFromWorkspaceDialog {

	public final static int TYPE_PATH = 0;
	public final static int TYPE_PACKAGE = 1;
	
	private Shell parentShell;
	
	private Shell folderselectshell = null;  //  @jve:decl-index=0:visual-constraint="10,10"
	private Composite foldertreecomposite = null;
	private Tree folderDirecTree = null;
	private Label label = null;
	private Text folderPath = null;
	private Label label1 = null;
	private Button okbutton = null;
	private Button cancelbutton = null;
	
	private int TYPE=TYPE_PATH;

	private IWorkspaceRoot workspaceRoot;
	
	private Path path = null;// 单击确定按钮时，所选中的文件夹绝对路径
	private String defaultFolder;
	private boolean prjOnly;
	
	public void setPrjOnly(boolean prjOnly) {
		this.prjOnly = prjOnly;
	}
	public String getDefaultFolder() {
		return defaultFolder;
	}
	public void setDefaultFolder(String defaultFolder) {
		this.defaultFolder = defaultFolder;
	}

	private String sepStr="/";
	
	public FolderFromWorkspaceDialog(Shell parentShell)
	{
		this.parentShell=parentShell;
	}
	
	
	
	public FolderFromWorkspaceDialog(Shell parentShell,int type)
	{
		this.parentShell=parentShell;
		this.TYPE = type;
		if(this.TYPE!=TYPE_PATH || this.TYPE!=TYPE_PACKAGE)
		{
			this.TYPE=TYPE_PATH;
		}
	}
	
	/**
	 * This method initializes sShell
	 */
	private void createSShell() {
		
		sepStr= this.TYPE==TYPE_PATH?"/":".";
		
		if(parentShell==null)
		{
			folderselectshell = new Shell();
		}
		else
		{
			folderselectshell = new Shell(parentShell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		}
		folderselectshell.setText("FolderSelect");
		createFoldertreecomposite();
		folderselectshell.setSize(new Point(601, 500));
		folderselectshell.setLayout(new FillLayout());
		folderselectshell.addShellListener(new org.eclipse.swt.events.ShellAdapter() {
			public void shellClosed(org.eclipse.swt.events.ShellEvent e) {
				path=null;
			}
		});
		
		selectDefaultFolder();
	}

	private void selectDefaultFolder() {
		if(this.defaultFolder==null || this.defaultFolder.trim().length()==0)
		{
			return ;
		}
		
		String[] paths=this.defaultFolder.split(this.sepStr);
		TreeItem item=null;
		for(int i = 0;i<paths.length ; i++)
		{
			TreeItem tempItem=null;
			if(i==0)
			{
				tempItem=findTreeItem(folderDirecTree, paths[i]);
			}
			else if(item!=null)
			{
				tempItem=findTreeItem(item, paths[i]);
			}
			
			if(tempItem!=null)
			{
				item=tempItem;
			}
			else
			{
				break;
			}
		}
		
	}



	/**
	 * This method initializes foldertreecomposite	
	 *
	 */
	private void createFoldertreecomposite() {
		foldertreecomposite = new Composite(folderselectshell, SWT.NONE);
		foldertreecomposite.setLayout(null);
		folderDirecTree = new Tree(foldertreecomposite, SWT.BORDER);
		folderDirecTree.setBounds(new Rectangle(8, 8, 566, 340));
		label = new Label(foldertreecomposite, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setBounds(new Rectangle(0, 396, 583, 17));
		label.setText("Label");
		folderPath = new Text(foldertreecomposite, SWT.BORDER);
		folderPath.setBounds(new Rectangle(98, 359, 474, 23));
		label1 = new Label(foldertreecomposite, SWT.NONE);
		label1.setBounds(new Rectangle(32, 361, 58, 17));
		label1.setText("Folder : ");
		okbutton = new Button(foldertreecomposite, SWT.NONE);
		okbutton.setText("OK");
		okbutton.setLocation(new Point(456, 419));
		okbutton.setSize(new Point(115, 27));
		okbutton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
			public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
				closeFolderSelectDialog();
			}
		});
		cancelbutton = new Button(foldertreecomposite, SWT.NONE);
		cancelbutton.setText("Cancel");
		cancelbutton.setSize(new Point(115, 27));
		cancelbutton.setLocation(new Point(318, 419));
		cancelbutton
				.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
					public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
						path=null;
						closeFolderSelectDialog();
					}
				});
		
		initFolderTree();
	}

	private void initFolderTree() {
		if(GlobalInfo.workspaceON)
		{
			initFolderTreeWorkspaceON();
		}
		else
		{
			initFolderTreeNormal();
		}
		
		// -------鼠标单击选择树的叶子节点时，在文本框中显示所选中的文件夹名---------------
		folderDirecTree.addListener(SWT.MouseDown, new Listener() {
			public void handleEvent(Event event) {
				Point point = new Point(event.x, event.y);
				TreeItem item = folderDirecTree.getItem(point);
				if ((item != null) && (item.getData() != null)) {
					folderPath.setText(getFolderPath(item));// 选中文件夹的同时在文本框中显示文件夹名
					// 选择的文件夹路径
					if(path==null)
					{
						path = new Path();
					}
					path.setDisplayPath(folderPath.getText());
					path.setAbsolutePath(getAbsoluteFolderPath(item));
					
				}
			}
		});
	}

	private void initFolderTreeNormal() {
		File file = new File(DBToolEngine.getWorkSpacePath());
		if(GlobalInfo.PRJ_NAME!=null)
		{
			file = new File(DBToolEngine.getWorkSpacePath()+"/"+GlobalInfo.PRJ_NAME);
		}
		File[] disks = file.listFiles();
		
		final Image folderImage = new Image(foldertreecomposite.getDisplay(),ImagePath.FLDR_OBJ);
		for (File folder : disks) {
			TreeItem sysdisknode = new TreeItem(folderDirecTree, 0);
			sysdisknode.setText(folder.getName());
			sysdisknode.setData(folder);// 保存当前节点数据
			sysdisknode.setImage(folderImage);
			new TreeItem(sysdisknode, 0);// 把当前节点作为目录节点
		}
		
		// ------展开树状结构时，显示相应目录下的系统文件夹（不显示面向用户隐藏的文件夹）节点-----------
		folderDirecTree.addListener(SWT.Expand, new Listener() {
			public void handleEvent(final Event event) {
				final TreeItem foldernode = (TreeItem) event.item;
				TreeItem[] items = foldernode.getItems();
				for (int i = 0; i < items.length; i++) {
					if (items[i].getData() != null)
						return;
					items[i].dispose();
				}
				File file = (File) foldernode.getData();
				File[] files = file.listFiles();// 返回File对象（文件夹与文件）的数组

				if (files == null || prjOnly)
					return;
				for (int i = 0; i < files.length; i++) {
					// 不显示隐藏文件的路径

					if ((files[i].isHidden() == false)
							&& (files[i].isFile() == false)) {// 判断当前路径是否为隐藏文件与文件夹
						TreeItem item = new TreeItem(foldernode, 0);
						item.setText(files[i].getName());
						// 叶子节点对应的数值为相应文件夹的File对象
						item.setData(files[i]);
						item.setImage(folderImage);// 设置文件夹图标
						// 当前为文件目录而不是文件的时候，添加新项目，以便只是显示文件夹（包括空文件夹），而不显示文件夹下的文件
						if (files[i].isDirectory()) {
							new TreeItem(item, 0);
						}
					}
				}
			}
		});
		
	}

	private void initFolderTreeWorkspaceON() {
		// TODO Auto-generated method stub
		
	}
	
	private String getFolderPath(TreeItem item)
	{
		if(item==null)
		{
			return "";
		}
		
		//递归获取路径
		String displayPath=getFolderPath(item.getParentItem());
		if(displayPath=="")
		{
			displayPath=item.getText();
		}
		else
		{
			displayPath+=sepStr+item.getText();
		}
		
		return displayPath;
	}
	
	private String getAbsoluteFolderPath(TreeItem item)
	{
		return ((File) item.getData()).getAbsolutePath();
	}

	/**
	 * 打开文件夹选择对话框
	 */
	public Path openFolderSelectDialog() {
		final Display display = Display.getDefault();
		createSShell();// 初始化文件夹选择对话框
		folderselectshell.open();// 打开文件夹选择窗口
		folderselectshell.layout();
		while (!folderselectshell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
//		display.dispose();
		
		return path;
	}
	
	/**
	 * 关闭文件夹选择对话框
	 */
	protected void closeFolderSelectDialog() {
		if (folderselectshell != null)
			folderselectshell.dispose();// 释放底层的资源
	}
	
	/**
	 * 在文件夹选择对话框中，单击确定按钮
	 */
	protected void selectFolder() {
		// 关闭当前窗口
		closeFolderSelectDialog();
	}
	
	protected TreeItem findTreeItem(Object parentCtr, String itemName)
	{
		TreeItem[] items=null;
		
		if(parentCtr instanceof Tree)
		{
			items=((Tree)parentCtr).getItems();
		}else if(parentCtr instanceof TreeItem)
		{
			items=((TreeItem)parentCtr).getItems();
		}
		
		if(items==null)
		{
			return null;
		}
		
		for(TreeItem item:items)
		{
			if(item.getText().equals(itemName))
			{
				return item;
			}
		}
		
		return null;
	}
	
	/**
	 * 文件夹选择对话框测试代码
	 */
	public static void main(String[] args) {
		FolderFromWorkspaceDialog fd = new FolderFromWorkspaceDialog(null);
		//fd.setPrjOnly(true);
		fd.openFolderSelectDialog();
	}
}
